package com.openatc.comm.common;

import com.google.gson.Gson;
import com.openatc.comm.data.MessageData;
import com.openatc.core.model.InnerError;

import java.util.logging.Level;
import java.util.logging.Logger;

import static com.openatc.comm.common.CosntDataDefine.erroranswer;
import static com.openatc.comm.common.CosntDataDefine.errorrask;

// 日志处理类
public class LogUtil {

    private static Gson gson = new Gson();
    // 针对不离线接口，接口应答的success消息，source 中带上这个字段
    public static final String SERVICE_RESPONSE_SUCCESS = "devs/message";

    // 根据配置文件设置comm模块的打印类型
    public static void SetLogLevelfromProp(Logger log){
        String level = PropertiesUtil.getStringProperty("logging.level.root");
        if (level == null)
            return;
        else if(level.equals("info")){
            log.setLevel(Level.INFO);
        }
        else if(level.equals("warning")) {
            log.setLevel(Level.WARNING);
        }
    }

    public static String BytePrintAsString(byte [] byteArray) {
        String temp = "";
        for (int i = 0; i < byteArray.length; i++) {
            String hex = Integer.toHexString(byteArray[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            temp += hex;
            temp += " ";
        }
        return temp;
    }
    public static String BytePrintAsString(byte [] byteArray, int length) {
        String temp = "";
        for (int i = 0; i < length; i++) {
            String hex = Integer.toHexString(byteArray[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            temp += hex;
            temp += " ";
        }
        return temp;
    }


    public static MessageData CreateErrorResponceData(String agentId, InnerError devCommError) {
        MessageData responceData = new MessageData();
        responceData.setAgentid(agentId);
        responceData.setOperation(erroranswer);
        responceData.setData(gson.toJsonTree(devCommError));
        return responceData;
    }

    public static MessageData CreateErrorRequestData(String agentId, InnerError devCommError) {
        MessageData responceData = new MessageData();
        responceData.setAgentid(agentId);
        responceData.setOperation(errorrask);
        responceData.setData(gson.toJsonTree(devCommError));
        return responceData;
    }

    public static MessageData CreateSuccessResponceData(String agentId,String operation,String infotype,String source) {
        MessageData responceData = new MessageData();
        responceData.setAgentid(agentId);
        responceData.setOperation(operation);
        responceData.setInfotype(infotype);
        if(source == null)
            source = SERVICE_RESPONSE_SUCCESS;
        responceData.setSource(source);
        return responceData;
    }
}
